package com.zdp.nio.selector;

import com.zdp.nio.channel.socketchannel.file.SocketClient;
import lombok.Builder;
import lombok.Data;
import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

@Builder
@Data
public class DiscardClient {
    @SneakyThrows
    public static void main(String[] args) {
        DiscardClient client = DiscardClient.builder()
                .ip("127.0.0.1")
                .port(9905)
                .build();
        for(int i =0;i<10;i++){
            client.send("Hello World" + i);
        }
    }

    private String ip;
    private Integer port;

    public void send(String msg) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(new InetSocketAddress(ip,port));
        while(!channel.finishConnect()){}
        // 写入数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(msg.getBytes());
        byteBuffer.flip();
        channel.write(byteBuffer);
        // 关闭
        channel.close();
    }

}
